﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
namespace Manager.CustomerHelper
{
   public class DistrictTree
    {
        //private static List<CustomMenu> _customMenus;
        private List<CustomDistrict> _customMenus;
        //public  void UpdateCustomMenus()
        //{
        //    _customMenus = null;
        //}
        public List<CustomDistrict> GetDistrictTree(string districtCode)
        {
            //if (_customMenus == null)
            //{

                //XMenuCollection items = new Select().From<XMenu>()
                //    .OrderAsc(XMenu.SortIndexColumn.ColumnName)
                //    .ExecuteAsCollection<XMenuCollection>();
                HW_DistrictManager manager = new HW_DistrictManager();
                //Menu BLL = new X_MenuBLL();
                IList<HW_District> items = manager.GetSubList(districtCode);
                List<CustomDistrict> newMenus = new List<CustomDistrict>();
                ResolveMenuCollection(items, newMenus, districtCode, 0);

                _customMenus = newMenus;
            //}

            return _customMenus;
        }
        private static int ResolveMenuCollection(IList<HW_District> oldMenus, List<CustomDistrict> newMenus, string parentId, int level)
        {
            int count = 0;
            foreach (HW_District menu in oldMenus)
            {
                if (menu.ParentDistrictCode == parentId)
                {
                    count++;

                    CustomDistrict my = new CustomDistrict();
                    newMenus.Add(my);
                    my.TreeLevel = level;
                    my.Id =menu.DistrictCode;
                    //my.ImageUrl = menu.ImageUrl;
                    my.Name = menu.Name;
                    //my.Title = menu.Title;
                    //my.NavigateUrl = menu.Url;
                    my.ParentId = menu.ParentDistrictCode;
                    //my.EnablePostback = true;
                    //my.Remark = menu.r;
                    //my.IsModule = menu.IsModule;
                    my.SortIndex = menu.Sort.HasValue ? menu.Sort.Value : 0;


                    level++;
                    int childCount = ResolveMenuCollection(oldMenus, newMenus, menu.DistrictCode, level);
                    if (childCount == 0)
                    {
                        my.IsTreeLeaf = true;
                    }
                    level--;
                }
            }
            //var self= oldMenus.Where(p => p.DistrictCode == parentId).Single();
            //newMenus.Add(new CustomDistrict() { 
            //    Id=self.DistrictCode,
            //    Name=self.Name,
            //    ParentId=self.ParentDistrictCode,
            //    SortIndex=self.Sort.HasValue ? self.Sort.Value : 0,
            //});
            return count;
        }
    }
}
